package com.example.onlinemusicserver2024.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.onlinemusicserver2024.common.R;
import com.example.onlinemusicserver2024.mapper.RankListMapper;
import com.example.onlinemusicserver2024.model.domain.RankList;
import com.example.onlinemusicserver2024.service.RankListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RankListServiceImpl extends ServiceImpl<RankListMapper, RankList> implements RankListService {
    @Autowired
    RankListMapper rankListMapper;

    @Override
    public R getUserRankList(int consumerId, int songListId) {
        // 设置查询条件
        QueryWrapper<RankList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("consumer_id", consumerId);
        queryWrapper.eq("song_list_id", songListId);
        List<RankList> rankLists = rankListMapper.selectList(queryWrapper);
        if (rankLists.size() > 0) {
            int score = rankLists.get(0).getScore();
            return R.success("查询成功", score);
        } else {
            return R.success("未评价");
        }

    }

    @Override
    public R getAvgScore(int songListId) {
        // 根据歌单ID获取所有的评分，再计算平均分
        QueryWrapper<RankList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("song_list_id", songListId);
        List<RankList> rankLists = rankListMapper.selectList(queryWrapper);
        int count = rankLists.size();
        if (count > 0) {
            int sum = 0;
            for (RankList r : rankLists) {
                int score = r.getScore();
                sum += score;
            }
            // 得到平均分
            double avgScore = sum / count;
            return R.success("查询平均分", avgScore);
        }
        return null;
    }

    @Override
    public R addRankList(RankList rankList) {
        int count = rankListMapper.insert(rankList);
        if(count > 0){
            return R.success("添加成功");
        }else{
            return R.error("添加失败");
        }

    }
}
